#pragma once
#include <odb/database.hxx>
#include <odb/mysql/database.hxx>

#include "logger.hpp"
#include "mysql.hpp"
// #include "friend_apply.hxx"
#include "friend_apply-odb.hxx"

namespace im{

    class FriendApplyTable {
        typedef odb::query<FriendApply> query;
        typedef odb::result<FriendApply> result;
    public:
        using ptr = std::shared_ptr<FriendApplyTable>;
        FriendApplyTable(const std::shared_ptr<odb::database>& db):_db(db){}

        // 新增好友申请
        bool insert(FriendApply &ev){
            try {
                odb::transaction trans(_db->begin());
                _db->persist(ev);
                trans.commit();
            }catch (std::exception &e) {
                LOG_CRITICAL("新增好友申请事件失败 {}-{}:{}！", ev.applicant_id(), ev.respondent_id(), e.what());
                return false;
            }
            return true;   
        }

        // 删除好友申请（处理完毕同意/拒绝的时候删除）       
        bool remove(const std::string& uid, const std::string& friend_uid){
            try{
                odb::transaction t(_db->begin());
                _db->erase_query<FriendApply>(query::applicant_id == uid && query::respondent_id == friend_uid);
                t.commit();
            } catch(const std::exception& e) {
                LOG_CRITICAL("删除好友申请事件失败 {}-{}:{}！", uid, friend_uid, e.what());
                return false;
            }
            return true; 
        }

        // 判断当前用户是否存在于指定用户的好友申请列表中
        bool exists(const std::string &uid, const std::string &pid) {
            bool flag = false;
            try {
                typedef odb::query<FriendApply> query;
                typedef odb::result<FriendApply> result;
                odb::transaction trans(_db->begin());
                result r(_db->query<FriendApply>(query::applicant_id == uid && query::respondent_id == pid));
                LOG_DEBUG("{} - {} 好友事件数量：{}", uid, pid, r.size());
                flag = !r.empty();
                trans.commit();
            }catch (std::exception &e) {
                LOG_CRITICAL("获取好友申请事件失败:{}-{}-{}！", uid, pid, e.what());
            }
            return flag;
        }

        //获取当前指定用户的 所有好友申请者ID
        std::vector<std::string> applyUsers(const std::string &uid){
            std::vector<std::string> res;
            try {
                odb::transaction trans(_db->begin());
                //当前的uid是被申请者的用户ID
                result r(_db->query<FriendApply>(query::respondent_id == uid));
                for (auto& i : r) {
                    res.push_back(i.applicant_id());
                }
                trans.commit();
            }catch (std::exception &e) {
                LOG_CRITICAL("通过用户{}的好友申请者失败:{}！", uid, e.what());
            }
            return res;
        }

    private:
        std::shared_ptr<odb::database> _db;
    };
}